package com.tianquan.server.handler;


import com.tianquan.common.instance.ServiceInstance;
import com.tianquan.common.message.ServiceRegistrationMessage;
import com.tianquan.server.registry.ServerInstanceManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @Author: tianquan
 * @date: 2024-11-03  10:30
 * @Description: 服务注册处理器器
 */
@Slf4j
@ChannelHandler.Sharable
public class ServiceRegisterMessageHandler extends SimpleChannelInboundHandler<ServiceRegistrationMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ServiceRegistrationMessage serviceRegistrationMessage) throws Exception {

        InetSocketAddress remoteSocketAddress = (InetSocketAddress) channelHandlerContext.channel().remoteAddress();
        String host = remoteSocketAddress.getHostName();
        int port = remoteSocketAddress.getPort();
        log.info("ServiceRegisterMessageHandler ====》 客户端IP: {},客户端端口: {}", host,port);

        ServiceInstance serviceInstance = serviceRegistrationMessage.getServiceInstance();
        serviceInstance.setHost(host);
        serviceInstance.setPort(port);
        ServerInstanceManager.registerInstance(serviceInstance.getServerName(), serviceInstance);
        log.info("服务注册成功:{}", serviceInstance);
    }

}
